<template>
  <!-- 导航栏 -->
  <div
    style="
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: move;
    "
    data-tauri-drag-region
  >
    <!-- 左上角按钮 -->
    <span style="position: absolute; left: 2%">
      <span class="titlebar-button" id="titlebar-option" @click="is_config">
        <el-icon v-if="is_display"><SettingOutlined /></el-icon>
        <el-icon v-else><RollbackOutlined /></el-icon>
      </span>
    </span>

    <!-- title -->
    <span style="color: green" data-tauri-drag-region>山羊专注</span>
    <!-- 最小化和关闭按钮 -->
    <span style="position: absolute; right: 2%">
      <span class="titlebar-button" id="titlebar-minimize" @click="minize">
        <el-icon><Minus /></el-icon>
      </span>
      <span class="titlebar-button" id="titlebar-close" @click="exit_windows">
        <el-icon><CloseBold /></el-icon>
      </span>
    </span>
  </div>
  <!-- 工作页 -->
  <div
    v-if="is_display"
    style="
      padding: 10% 5% 0% 5%;
      display: flex;
      flex-direction: column;
      align-items: center;
    "
  >
    <el-progress
      type="circle"
      :percentage="percentage_num"
      :stroke-width="int_four"
      :status="circle_status"
    >
      <template #default="{ percentage }">
        <div class="percentage-value" style="color: white; font-size: 30px">
          {{ remain_str }}
        </div>
        <br />
        <div class="percentage-label" style="color: white">
          {{ main_str }}
        </div>
      </template>
    </el-progress>

    <el-icon
      v-if="is_play"
      size="50px"
      style="padding-top: 10px"
      @click="become_stop"
      class="click_button"
      ><VideoPause
    /></el-icon>
    <el-icon
      v-else
      size="50px"
      style="padding-top: 10px"
      @click="become_run"
      class="click_button"
      ><VideoPlay
    /></el-icon>
    <!-- 底部按钮和提示:循环次数 -->
    <div
      style="
        position: fixed;
        left: 15px;
        bottom: 15px;
        color: #b3acac;
        font-size: 12px;
      "
    >
      循环:{{ current_loop_number }}/{{ loop_number }} <br />
      音量: {{ volume }}% <br />
      专注时间:{{ focus_time }}分钟 <br />短歇时间:{{ break_time }}分钟
    </div>
    <!-- 底部按钮和提示:重新从第一个周期开始 -->
    <el-tooltip content="从头开始" placement="top" :hide-after="int_zero">
      <el-icon
        size="18px"
        style="position: fixed; right: 80px; bottom: 25px; color: #b3acac"
        @click="all_reset"
        class="click_button click_button_buttom"
        ><FastBackwardOutlined
      /></el-icon>
    </el-tooltip>
    <!-- 底部按钮和提示:本次循环重置 -->
    <el-tooltip content="重置当前节" placement="top" :hide-after="int_zero">
      <el-icon
        size="18px"
        style="position: fixed; right: 50px; bottom: 25px; color: #b3acac"
        @click="current_reset"
        class="click_button click_button_buttom"
        ><RefreshRight
      /></el-icon>
    </el-tooltip>
    <!-- 底部按钮和提示:next -->
    <el-tooltip content="下一节" placement="top" :hide-after="int_zero">
      <el-icon
        size="20px"
        style="position: fixed; right: 20px; bottom: 25px; color: #b3acac"
        @click="next_step"
        class="click_button click_button_buttom"
        ><StepForwardFilled
      /></el-icon>
    </el-tooltip>
  </div>
  <!-- 配置页面 -->
  <div
    v-else
    style="
      padding: 5% 5% 0% 5%;
      display: flex;
      flex-direction: column;
      align-items: center;
    "
  >
    <!-- 设置专注时间 -->
    <div style="font-size: small; padding-top: 0px">
      专注时间：{{ focus_time }} 分钟
    </div>

    <el-slider
      v-model="focus_time"
      class="slider-red"
      :step="5"
      :min="focus_time_min"
      :max="focus_time_max"
      :show-tooltip="bool_false"
    />
    <!-- 设置短歇时间 -->
    <div style="font-size: small; padding-top: 10px">
      短歇时间：{{ break_time }} 分钟
    </div>
    <el-slider
      v-model="break_time"
      class="slider-green"
      :step="5"
      :min="break_time_min"
      :max="break_time_max"
      :show-tooltip="bool_false"
    />
    <!-- 设置循环次数 -->
    <div style="font-size: small; padding-top: 10px">
      循环次数：{{ loop_number }} 次
    </div>
    <el-slider
      v-model="loop_number"
      class="slider-blue"
      :step="1"
      :min="loop_number_min"
      :max="loop_number_max"
      :show-tooltip="bool_false"
    />
    <!-- 设置音量 -->
    <div style="font-size: small; padding-top: 10px">音量：{{ volume }} %</div>
    <el-slider
      v-model="volume"
      class="slider-volume"
      :step="10"
      :min="0"
      :max="100"
      :show-tooltip="bool_false"
    />
    <!-- 选择背景音：专注 -->
    <div style="padding-top: 10px">
      <span style="position: relative; font-size: 13px">专注：&nbsp; </span>
      <el-radio-group v-model="focus_background_voice" size="small">
        <el-radio :value="no_voice" size="small">无背景声</el-radio>
        <!-- <el-radio :value="beijing_1" size="small">背景声1</el-radio> -->
        <el-radio :value="beijing_2" size="small">有背景声</el-radio>
      </el-radio-group>
    </div>
    <!-- 选择背景音：短歇 -->
    <div>
      <span style="position: relative; font-size: 13px">短歇：&nbsp; </span>
      <el-radio-group v-model="break_background_voice" size="small">
        <el-radio :value="no_voice" size="small">无背景声</el-radio>
        <!-- <el-radio :value="beijing_1" size="small">背景声1</el-radio> -->
        <el-radio :value="beijing_2" size="small">有背景声</el-radio>
      </el-radio-group>
    </div>
    <!-- 选择背景音：提醒 -->
    <div>
      <el-tooltip
        content="倒计时为0时触发"
        placement="bottom"
        :hide-after="int_zero"
      >
        <span style="position: relative; font-size: 13px">提醒：&nbsp; </span>
      </el-tooltip>
      <el-radio-group v-model="notice_voice" size="small">
        <el-radio :value="no_voice" size="small">无提醒声</el-radio>
        <!-- <el-radio :value="tishi_1" size="small">提醒声1</el-radio> -->
        <el-radio :value="tishi_2" size="small">有提醒声</el-radio>
      </el-radio-group>
    </div>

    <div style="padding-top: 25px; font-size: small; position: relative">
      <el-button type="primary" link @click="reset_click">
        恢复默认设置</el-button
      >
      <el-button @click="drawer = true" link> 关于本软件 </el-button>
    </div>
  </div>

  <el-drawer
    v-model="drawer"
    direction="btt"
    :with-header="false"
    class="drawer_class"
    size="70%"
  >
    <ol>
      <li>本软件免费</li>
      <li>本软件不联网</li>
      <li>本软件不操作任何文件</li>
      <li>本软件不读写剪切板</li>
      <li>
        <a
          style="color: #ffffff; font-weight: bold"
          href="#"
          @click.prevent="openLink('https://gitee.com/xiaoshanyangcode')"
          >作者主页</a
        >
      </li>
      <li>软件版本：1.0.2</li>
      <li>感谢：Pomotroid（github）</li>
      <li>感谢每一位用户</li>
    </ol>
  </el-drawer>
</template>

<script setup>
import {
  Minus,
  CloseBold,
  VideoPause,
  VideoPlay,
  RefreshRight,
} from "@element-plus/icons-vue";
import {
  StepForwardFilled,
  FastBackwardOutlined,
  SettingOutlined,
  RollbackOutlined,
} from "@ant-design/icons-vue";

import {
  WebviewWindow,
  getAllWebviewWindows,
} from "@tauri-apps/api/webviewWindow";
import { ref, onMounted, watch } from "vue";
// 音频文件的base64编码
import {
  no_voice,
  tishi_2,
  beijing_2,
  img_book_64,
  img_break_64,
  img_stop_64,
  img_success_64,
  img_start_64,
  img_exit_64,
  img_backward_64,
  click_voice,
} from "./assets/music.js";
// tray相关
import { TrayIcon } from "@tauri-apps/api/tray";
import { Menu } from "@tauri-apps/api/menu";
import {
  base64ToUint8Array,
  huizhi_tray_break,
  huizhi_tray_focus,
} from "./assets/tray.js";
// 浏览器打开超链接
import { open } from "@tauri-apps/plugin-shell";

// 是在显示页面，还是配置页面
const is_display = ref(true);
//  是否在运行，默认是暂停
const is_play = ref(false);
//  是否在专注时间，默认为时
const is_focus = ref(true);
//  专注时间，休息时间，循环次数
const focus_time = ref(45);
const focus_time_min = ref(5);
const focus_time_max = ref(120);
const break_time = ref(5);
const break_time_min = ref(5);
const break_time_max = ref(120);
const loop_number = ref(3);
const loop_number_min = ref(1);
const loop_number_max = ref(10);
const current_loop_number = ref(1);
const remain_secent = ref(0);
const remain_minute = ref(0);
const total_secent = ref(2700);
const volume = ref(50);
//  默认为exception（红色，表示专注时间），歇息时值为：success
const circle_status = ref("exception");
//  剩余时间，默认值要计算
const remain_str = ref("45:00");
const percentage_num = ref(100);

// 中心字符
const main_str = ref("专注时间");
const focus_background_voice = ref(no_voice);
const break_background_voice = ref(beijing_2);
const notice_voice = ref(tishi_2);
// 真正运行的声音，动态调整
const playing_voice = ref("");

const int_four = ref(4);
const int_zero = ref(0);
const bool_false = ref(false);

// tray
const img_book = new Image();
const img_break = new Image();
const is_set_tray_menu = ref(false);
// 是否全部任务已完成
const is_done = ref(false);
// 关于本软件的提示页面
const drawer = ref(false);

const openLink = async (url) => {
  await open(url);
};

watch(focus_time, () => {
  if (is_focus.value) {
    is_play.value = false;
    total_secent.value = focus_time.value * 60;
    percentage_num.value = 100;
    remain_str.value = focus_time.value.toString().padStart(2, "0") + ":00";
    is_set_tray_menu.value = false;
    tray_status_stop();
  }
  update_success();
});
watch(break_time, () => {
  if (!is_focus.value) {
    is_play.value = false;
    total_secent.value = break_time.value * 60;
    percentage_num.value = 100;
    remain_str.value = break_time.value.toString().padStart(2, "0") + ":00";
    is_set_tray_menu.value = false;
    tray_status_stop();
  }
  update_success();
});
watch(loop_number, () => {
  update_success();
});
watch(volume, () => {
  update_success();
});
watch(focus_background_voice, () => {
  update_success();
});
watch(break_background_voice, () => {
  update_success();
});
watch(notice_voice, () => {
  update_success();
});

const playMusic = async () => {
  if (playing_voice.value.length > 2 && is_play.value) {
    const local_music = new Audio(
      `data:audio/mpeg;base64,${playing_voice.value}`
    );
    local_music.volume = (volume.value / 100).toFixed(1);
    local_music.play();
  }
};

// 跳过本节
const next_step = () => {
  playMusic_click();
  if (is_focus.value) {
    is_focus.value = false;
    main_str.value = "短歇时间";
    total_secent.value = break_time.value * 60;
    circle_status.value = "success";
    percentage_num.value = 100;
    remain_str.value = String(break_time.value) + ":00";
  } else if (loop_number.value != current_loop_number.value) {
    current_loop_number.value++;
    is_focus.value = true;
    main_str.value = "专注时间";
    total_secent.value = focus_time.value * 60;
    circle_status.value = "exception";
    percentage_num.value = 100;
    remain_str.value = String(focus_time.value) + ":00";
  }
};

// 重置本节
const current_reset = () => {
  playMusic_click();
  if (is_focus.value) {
    total_secent.value = focus_time.value * 60;
    remain_str.value = String(focus_time.value) + ":00";
  } else {
    total_secent.value = break_time.value * 60;
    remain_str.value = String(break_time.value) + ":00";
  }
  percentage_num.value = 100;
  is_done.value = false;
};

//  从第一节开始
const all_reset = () => {
  playMusic_click();
  is_focus.value = true;
  main_str.value = "专注时间";
  total_secent.value = focus_time.value * 60;
  circle_status.value = "exception";
  percentage_num.value = 100;
  current_loop_number.value = 1;
  is_done.value = false;
  remain_str.value = String(focus_time.value) + ":00";
  if (is_play.value) {
    become_run();
  } else {
    become_stop();
  }
};
// 修改成功
const update_success = () => {
  ElMessage({
    message: "更新成功",
    type: "success",
    duration: 1000,
    center: true,
    grouping: true,
    offset: 8,
  });
};

// 点击按钮的声效
const playMusic_click = () => {
  const local_music_click = new Audio("data:audio/mpeg;base64," + click_voice);
  local_music_click.volume = (volume.value / 100).toFixed(1);
  local_music_click.play();
};

const become_run = () => {
  playMusic_click();
  is_play.value = true;
  is_set_tray_menu.value = false;
};
const become_stop = () => {
  playMusic_click();
  is_play.value = false;
  tray_status_stop();
  is_set_tray_menu.value = false;
};

const daojishi = async () => {
  const intervalId = setInterval(async () => {
    if (total_secent.value == 0) {
      if (is_focus.value) {
        is_focus.value = false;
        main_str.value = "短歇时间";
        total_secent.value = break_time.value * 60;
        circle_status.value = "success";
      } else if (loop_number.value != current_loop_number.value) {
        current_loop_number.value++;
        is_focus.value = true;
        main_str.value = "专注时间";
        total_secent.value = focus_time.value * 60;
        circle_status.value = "exception";
      } else {
        is_play.value = false;
        main_str.value = "任务完成！";
        // 只执行一次
        if (!is_done.value) {
          is_set_tray_menu.value = false;
          is_done.value = true;
          await tray_status_success();
        }
      }
    }

    if (total_secent.value != 0) {
      total_secent.value--;
      //  暂停就不减少数据
      if (!is_play.value) {
        total_secent.value++;
      }
    }

    remain_minute.value = Math.floor(total_secent.value / 60);
    remain_secent.value = total_secent.value % 60;
    remain_str.value =
      remain_minute.value.toString().padStart(2, "0") +
      ":" +
      remain_secent.value.toString().padStart(2, "0");
    if (is_focus.value) {
      percentage_num.value = Math.floor(
        (total_secent.value * 100) / (focus_time.value * 60)
      );
      if (total_secent.value > 1) {
        playing_voice.value = focus_background_voice.value;
        playMusic();
      }
      if (is_play.value) {
        await tray_focus(percentage_num.value);
      }
    } else {
      percentage_num.value = Math.floor(
        (total_secent.value * 100) / (break_time.value * 60)
      );
      if (total_secent.value > 1) {
        playing_voice.value = break_background_voice.value;
        playMusic();
      }
      if (is_play.value) {
        await tray_break(percentage_num.value);
      }
    }
    // 倒计时为0时通知，提前1秒运行
    if (total_secent.value == 1 && is_play.value) {
      playing_voice.value = notice_voice.value;
      playMusic();
    }
  }, 1000);
};

onMounted(async () => {
  // 禁用右键，调试完加此设置
  document.addEventListener("contextmenu", (e) => {
    e.preventDefault();
  });

  img_book.src = img_book_64;
  img_break.src = img_break_64;
  // const menu = await Menu.new({
  //   items: [
  //     {
  //       id: "quit",
  //       text: "退出",
  //       action: exit_windows,
  //       icon: base64ToUint8Array(img_exit_64),
  //     },
  //     {
  //       id: "restart",
  //       text: "从头开始",
  //       action: all_reset,
  //       icon: base64ToUint8Array(img_backward_64),
  //     },
  //     {
  //       id: "stop",
  //       text: "暂停",
  //       action: become_stop,
  //       icon: base64ToUint8Array(img_start_64),
  //     },
  //     {
  //       id: "start",
  //       text: "开始",
  //       action: become_run,
  //       icon: base64ToUint8Array(img_stop_64),
  //     },
  //   ],
  // });
  const options = {
    icon: null,
    id: "1",
    // menu,
  };
  await TrayIcon.new(options);

  await tray_status_stop();
  await daojishi();
  const appWindow = await WebviewWindow.getByLabel("main");
  await appWindow.show();
});

const tray_status_stop = async () => {
  const tray_instance = await TrayIcon.getById("1");
  const new_tray_icon = base64ToUint8Array(img_stop_64);
  tray_instance.setIcon(new_tray_icon);
  tray_instance.setTooltip("暂停中！（山羊专注）");
  if (!is_set_tray_menu.value) {
    is_set_tray_menu.value = true;
    const menu = await Menu.new({
      items: [
        {
          id: "title",
          text: "山羊专注",
          enabled: false,
        },
        {
          id: "quit",
          text: "退出",
          action: exit_windows,
          icon: base64ToUint8Array(img_exit_64),
        },
        {
          id: "start",
          text: "开始",
          action: become_run,
          icon: base64ToUint8Array(img_stop_64),
        },
      ],
    });
    tray_instance.setMenu(menu);
  }
};

const tray_status_success = async () => {
  const tray_instance = await TrayIcon.getById("1");
  const new_tray_icon = base64ToUint8Array(img_success_64);
  tray_instance.setIcon(new_tray_icon);
  tray_instance.setTooltip("任务完成！恭喜！（山羊专注）");
  if (!is_set_tray_menu.value) {
    is_set_tray_menu.value = true;
    const menu = await Menu.new({
      items: [
        {
          id: "title",
          text: "山羊专注",
          enabled: false,
        },
        {
          id: "quit",
          text: "退出",
          action: exit_windows,
          icon: base64ToUint8Array(img_exit_64),
        },
        {
          id: "restart",
          text: "重新开始",
          action: all_reset,
          icon: base64ToUint8Array(img_backward_64),
        },
      ],
    });
    tray_instance.setMenu(menu);
  }
};

const tray_focus = async (baifenbi) => {
  const tray_instance = await TrayIcon.getById("1");
  const new_tray_icon = await huizhi_tray_focus(baifenbi, img_book);
  tray_instance.setIcon(new_tray_icon);
  tray_instance.setTooltip("专注时间！（山羊专注）");
  if (!is_set_tray_menu.value) {
    is_set_tray_menu.value = true;
    const menu = await Menu.new({
      items: [
        {
          id: "title",
          text: "山羊专注",
          enabled: false,
        },
        {
          id: "quit",
          text: "退出",
          action: exit_windows,
          icon: base64ToUint8Array(img_exit_64),
        },
        {
          id: "stop",
          text: "暂停",
          action: become_stop,
          icon: base64ToUint8Array(img_start_64),
        },
      ],
    });
    tray_instance.setMenu(menu);
  }
};
const tray_break = async (baifenbi) => {
  const tray_instance = await TrayIcon.getById("1");
  const new_tray_icon = await huizhi_tray_break(baifenbi, img_break);
  tray_instance.setIcon(new_tray_icon);
  tray_instance.setTooltip("短歇时间！（山羊专注）");
  if (!is_set_tray_menu.value) {
    is_set_tray_menu.value = true;
    const menu = await Menu.new({
      items: [
        {
          id: "title",
          text: "山羊专注",
          enabled: false,
        },
        {
          id: "quit",
          text: "退出",
          action: exit_windows,
          icon: base64ToUint8Array(img_exit_64),
        },
        {
          id: "stop",
          text: "暂停",
          action: become_stop,
          icon: base64ToUint8Array(img_start_64),
        },
      ],
    });

    tray_instance.setMenu(menu);
  }
};

const reset_click = () => {
  playMusic_click();
  update_success();
  focus_time.value = 45;
  break_time.value = 5;
  loop_number.value = 3;
  volume.value = 50;
  notice_voice.value = tishi_2;
  focus_background_voice.value = no_voice;
  break_background_voice.value = beijing_2;
  is_done.value = false;
};

const is_config = () => {
  is_display.value = !is_display.value;
};

const minize = async () => {
  const appWindow = await WebviewWindow.getByLabel("main");
  appWindow.minimize();
};

const exit_windows = async () => {
  const appWindow = await WebviewWindow.getByLabel("main");
  appWindow.close();
};
</script>

<style scoped>
.titlebar-button {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 30px;
  height: 30px;
  color: rgb(117, 117, 108);
}
.titlebar-button:hover {
  background: #464a4a;
  cursor: pointer;
  color: #121212;
}

.click_button:hover {
  cursor: pointer;
  color: rgb(172, 233, 242);
}
.click_button_buttom:hover {
  border: #464a4a 1px solid;
}
</style>

<style>
body,
.drawer_class {
  background-color: #242433;
  color: #ffffff; /* 文字颜色 */
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  user-select: none;
}
.slider-blue,
.slider-red,
.slider-volume,
slider-green {
  position: relative;
}

.slider-red .el-slider__runway .el-slider__bar {
  background-color: red !important;
  height: 2px;
}
.slider-green .el-slider__runway .el-slider__bar {
  background-color: green !important;
  height: 2px;
}
.slider-blue .el-slider__runway .el-slider__bar {
  background-color: rgb(19, 177, 220) !important;
  height: 2px;
}
.slider-volume .el-slider__runway .el-slider__bar {
  background-color: rgb(117, 117, 108) !important;
  height: 2px;
}
.slider-blue .el-slider__runway,
.slider-red .el-slider__runway,
.slider-green .el-slider__runway,
.slider-volume .el-slider__runway {
  background-color: black;
  height: 2px;
}

.slider-red .el-slider__runway .el-slider__button-wrapper > div {
  position: absolute;
  top: 12px;
  border-color: red;
  background-color: red;
  height: 8px;
  width: 8px;
}
.slider-green .el-slider__runway .el-slider__button-wrapper > div {
  position: absolute;
  top: 12px;
  border-color: green;
  background-color: green;
  height: 8px;
  width: 8px;
}
.slider-blue .el-slider__runway .el-slider__button-wrapper > div {
  position: absolute;
  top: 12px;
  border-color: rgb(19, 177, 220);
  background-color: rgb(19, 177, 220);
  height: 8px;
  width: 8px;
}
.slider-volume .el-slider__runway .el-slider__button-wrapper > div {
  position: absolute;
  top: 12px;
  right: 16px;
  border-color: rgb(117, 117, 108);
  background-color: rgb(117, 117, 108);
  height: 8px;
  width: 8px;
}
.el-slider {
  height: 20px !important;
}

/* 调整圆形的大小 */
.el-progress-circle {
  width: 200px !important;
  height: 200px !important;
}

.el-radio {
  margin-right: 25px !important;
}
.el-radio__label {
  padding-left: 4px !important;
  color: #979ba4 !important;
}
</style>
